//
//  WSQSelectionView.m
//  RACTest
//
//  Created by 翁胜琼 on 2018/10/12.
//  Copyright © 2018 翁胜琼. All rights reserved.
//

#import "WSQHelper.h"
#import "WSQSelectionView.h"
#import "WSQSelectionViewRoundedRectCell.h"
#import <Masonry/Masonry.h>

static NSString * const cellID = @"WSQSelectionViewRoundedRectCell";


@interface WSQSelectionView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    UIColor *_cellNormalTitleColor;        // cell normal 文字颜色,默认黑色
    UIColor *_cellSelectedTitleColor;        // cell selected 文字颜色,默认红色
    UIImage *_cellNormalBackgroundImage;   // cell normal 背景图片
    UIImage *_cellSelectedBackgroundImage;   // cell selected 背景偷拍你
    UIColor *_cellNormalBackgroundColor;   // cell normal 背景颜色，默认白色
    UIColor *_cellSelectedBackgroundColor;  // cell selected 背景颜色,默认黄色
    
    UICollectionViewFlowLayout *_flowLayout;
}

@property (nonatomic,strong) UICollectionView *collectionView;

@end

@implementation WSQSelectionView

- (instancetype)initWithFrame:(CGRect)frame
                        items:(NSArray<WSQSelectionItem *> *)items
               preferredStyle:(WSQSelectionViewStyle)style
{
    if (self = [super init])
    {
        self.frame = frame;
        _items = items;
        _style = style;
        [self setupUI];
        [self setupDefaultValue];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        self.frame = frame;
        [self setupUI];
        [self setupDefaultValue];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupUI];
        [self setupDefaultValue];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setupUI];
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        // 设置默认值
        [self setupDefaultValue];
    }
    return self;
}

- (void)reloadData
{
    [self.collectionView reloadData];
}

// MARK: - CollectionViewDelegate && collectionViewDataSource
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger item = indexPath.item;
    WSQSelectionItem *targetItem = self.items[item];
    // 是否是选择的 item
    BOOL isSelectedItem = [self.selectedItems containsObject:targetItem];
    UIColor *titleColor = isSelectedItem ? _cellSelectedTitleColor : _cellNormalTitleColor;
    UIColor *backgroundColor = isSelectedItem ? _cellSelectedBackgroundColor : _cellNormalBackgroundColor;
    UIImage *backgroundImage = isSelectedItem ? _cellSelectedBackgroundImage : _cellNormalBackgroundImage;
    
    WSQSelectionViewRoundedRectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    [cell setItem:targetItem];
    
    [cell setTitleColor:titleColor
               fontsize:_titleLabelFontsize
           cornerRadius:_cellCornerRadius
        backgroundColor:backgroundColor
        backgroundImage:backgroundImage];
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.items.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
    
}

// MARK: - setupUI
- (void)setupUI
{
    [self setupCollectionView];
}

// 设置默认值
- (void)setupDefaultValue
{
    _numberOfColumn = 4;
    _minimumLineSpacing = 12;
    _minimumInteritemSpacing = 16;
    _allowsSelection = true;
    _allowsMultipleSelection = false;
    _isScrollEnabled = true;
    _contentInset = UIEdgeInsetsZero;
    
    _cellHeight = 25;
    _cellCornerRadius = 0;
    _titleLabelFontsize = 14;
    
    _cellNormalBackgroundImage = nil;
    _cellSelectedBackgroundImage = nil;
    _cellNormalTitleColor = [UIColor blackColor];
    _cellSelectedTitleColor = [UIColor redColor];
    _cellNormalBackgroundColor = [UIColor whiteColor];
    _cellSelectedBackgroundColor = [UIColor yellowColor];
    
    _selectedItems = [NSArray array];
}

// 设置 collectionview
- (void)setupCollectionView
{
    CGFloat viewWidth = self.frame.size.width;
    CGFloat viewHeight = self.frame.size.height;
    CGFloat collectionViewWidth = viewWidth - _contentInset.left - _contentInset.right;
    CGFloat collectionViewHeight = viewHeight - _contentInset.top - _contentInset.bottom;
    CGRect collectionViewFrame = CGRectMake(_contentInset.left, _contentInset.top, collectionViewWidth, collectionViewHeight);

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = [self getLayoutItemSize];
    layout.minimumLineSpacing = _minimumLineSpacing;
    layout.minimumInteritemSpacing = _minimumInteritemSpacing;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _flowLayout = layout;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self addSubview:_collectionView];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(self->_contentInset.top);
        make.left.equalTo(self).offset(self->_contentInset.left);
        make.bottom.equalTo(self).offset(self->_contentInset.bottom);
        make.right.equalTo(self).offset(self->_contentInset.right);
    }];
    
    // registerCollectionViewCell
    [self registerCollectionViewCell];
}

- (CGSize)getLayoutItemSize
{
    CGFloat viewWidth = self.bounds.size.width;
    CGFloat collectionViewWidth = viewWidth - _contentInset.left - _contentInset.right;
    CGFloat cellWidth = (collectionViewWidth - (_numberOfColumn - 1)*_minimumInteritemSpacing)/_numberOfColumn - 1;
    
    return CGSizeMake(cellWidth, _cellHeight);
}

- (void)registerCollectionViewCell
{
    [_collectionView registerNib:[UINib nibWithNibName:@"WSQSelectionViewRoundedRectCell" bundle:nil] forCellWithReuseIdentifier:cellID];
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger item = indexPath.item;
    WSQSelectionItem *selectedItem = _items[item];
    NSMutableArray *mutableSelectedItems = [_selectedItems mutableCopy];
    
    if (self.allowsMultipleSelection == false)  // 单选
    {
        // 获取上一个被选中的 item
        if ([_items containsObject:_selectedItems.firstObject])
        {
            NSInteger lastSelectionItemRow = [_items indexOfObjectIdenticalTo:_selectedItems.firstObject];
            [mutableSelectedItems setObject:selectedItem atIndexedSubscript:0];

            [self setSelectedItems:mutableSelectedItems];
            // 清除上一个被选中的 item
            [self checkCelSatteAtIndexPath:[NSIndexPath indexPathForRow:lastSelectionItemRow inSection:0]];
        }else
        {
            [mutableSelectedItems setObject:selectedItem atIndexedSubscript:0];
            [self setSelectedItems:mutableSelectedItems];
        }
    }else       // 多选
    {
        [mutableSelectedItems addObject:selectedItem];
        self.selectedItems = [mutableSelectedItems copy];
    }
    [self checkCelSatteAtIndexPath:indexPath];
    if (self.didSelectedItemBlock)
    {
        self.didSelectedItemBlock(selectedItem);
    }
}


- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger item = indexPath.item;
    WSQSelectionItem *deselectedItem = _items[item];
    NSMutableArray *mutableSelectedItems = [_selectedItems mutableCopy];
    [mutableSelectedItems removeObject:deselectedItem];
    _selectedItems = [mutableSelectedItems copy];
    [self checkCelSatteAtIndexPath:indexPath];
}

// 检查 cell 选中状态
- (void)checkCelSatteAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL isSelected;
    NSInteger item = indexPath.item;
    WSQSelectionItem *targetItem = _items[item];
    // selectedItem 是否包含 targetItem
    isSelected = [_selectedItems containsObject:targetItem];
    [self updateCellAppearanceAtIndexPath:indexPath withSelectedState:isSelected];
}

// 更新 cell 外观
- (void)updateCellAppearanceAtIndexPath:(NSIndexPath *)indexpath withSelectedState:(BOOL)isSelected
{
    UIColor *titleColor = isSelected ? _cellSelectedTitleColor : _cellNormalTitleColor;
    UIColor *backgroundColor = isSelected ? _cellSelectedBackgroundColor : _cellNormalBackgroundColor;
    UIImage *backgroundImage = isSelected ? _cellSelectedBackgroundImage : _cellNormalBackgroundImage;
    
    switch (_style) {
        case WSQSelectionViewRoundedRect:
        {
            WSQSelectionViewRoundedRectCell *cell = (WSQSelectionViewRoundedRectCell *)[_collectionView cellForItemAtIndexPath:indexpath];
            [cell setTitleColor:titleColor
                       fontsize:0
                   cornerRadius:0
                backgroundColor:backgroundColor
                backgroundImage:backgroundImage];
        }
            break;
            
        default:
            break;
    }
}

// MARK: - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_numberOfColumn == 0)
    {
        WSQSelectionItem *item = self.items[indexPath.row];
        CGSize itemSize = [WSQHelper getLabelSiex:item.title font:[UIFont fontWithName:@"PingFang SC" size:_titleLabelFontsize] maxSize:CGSizeMake(CGFLOAT_MAX, _cellHeight)];
        CGSize itemFitSize = CGSizeMake(itemSize.width + 16, _cellHeight);
        return itemFitSize;
    }else
    {
        return [self getLayoutItemSize];
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return _minimumLineSpacing;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return _minimumInteritemSpacing;
}

// MARK: - private method
- (void)setNumberOfColumn:(NSInteger)numberOfColumn
       minimumLineSpacing:(CGFloat)minimumLineSpacing
  minimumInteritemSpacing:(CGFloat)minimumInteritemSpacing
             contentInset:(UIEdgeInsets)contentInset
               cellHeight:(CGFloat)cellHeight
         cellCornerRadius:(CGFloat)cellCornerRadius
       titleLabelFontsize:(CGFloat)titleLabelFontsize
{
    _numberOfColumn = numberOfColumn;
    _minimumLineSpacing = minimumLineSpacing;
    _minimumInteritemSpacing = minimumInteritemSpacing;
    _contentInset = contentInset;
    _cellHeight = cellHeight;
    _cellCornerRadius = cellCornerRadius;
    _titleLabelFontsize = titleLabelFontsize;
    
}

- (void)setTitleColor:(UIColor *)color
      backgroundColor:(UIColor *)backgroundColor
      backgroundImage:(UIImage *)backgroundImage
             forState:(UIControlState)state
{
    if (state == UIControlStateNormal)
    {
        _cellNormalTitleColor = color;
        _cellNormalBackgroundColor = backgroundColor;
        _cellNormalBackgroundImage = backgroundImage;
    }else if (state == UIControlStateSelected)
    {
        _cellSelectedTitleColor = color;
        _cellSelectedBackgroundColor = backgroundColor;
        _cellSelectedBackgroundImage = backgroundImage;
    }
    [self reloadData];
}
// MARK: - getter
- (NSInteger)suggestViewHeight
{
    if (_numberOfColumn == 0)
    {
        [self reloadData];
        [self setNeedsLayout];
        [self layoutIfNeeded];
        _suggestViewHeight = self.collectionView.collectionViewLayout.collectionViewContentSize.height;
    }else
    {
        NSInteger viewHeight = ceil(((double)self.items.count) / _numberOfColumn);    // 向上取整
        _suggestViewHeight = viewHeight;
    }
    return _suggestViewHeight;
}

// MARK: - setter
- (void)setItems:(NSArray<WSQSelectionItem *> *)items
{
    _items = items;
    [self reloadData];
}

- (void)setStyle:(WSQSelectionViewStyle)style
{
    _style = style;
    [self reloadData];
}

- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state
{
    if (state == UIControlStateNormal)
    {
        _cellNormalTitleColor = color;
    }else if (state == UIControlStateSelected)
    {
        _cellSelectedTitleColor = color;
    }
    [self reloadData];
}

- (void)setBackgroundColor:(UIColor *)color forState:(UIControlState)state
{
    if (state == UIControlStateNormal)
    {
        _cellNormalBackgroundColor = color;
    }else if (state == UIControlStateSelected)
    {
        _cellSelectedBackgroundColor = color;
    }
    [self reloadData];
}

-(void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state
{
    if (state == UIControlStateNormal)
    {
        _cellNormalBackgroundImage = image;
    }else if (state == UIControlStateSelected)
    {
        _cellSelectedBackgroundImage = image;
    }
    [self reloadData];
}

- (void)setIsScrollEnabled:(BOOL)isScrollEnabled
{
    _isScrollEnabled = isScrollEnabled;
    _collectionView.scrollEnabled = isScrollEnabled;
}

- (void)setAllowsSelection:(BOOL)allowsSelection
{
    _allowsSelection = allowsSelection;
    _collectionView.allowsSelection = allowsSelection;
}

- (void)setAllowsMultipleSelection:(BOOL)allowsMultipleSelection
{
    _allowsMultipleSelection = allowsMultipleSelection;
    _collectionView.allowsMultipleSelection = allowsMultipleSelection;
}

- (void)setNumberOfColumn:(NSInteger)numberOfColumn
{
    _numberOfColumn = numberOfColumn;
//    if (numberOfColumn == 0)
//    {
//        self.collectionView.delegate = self;
//    }else
//    {
//        _flowLayout.itemSize = [self getLayoutItemSize];
//        [_collectionView setCollectionViewLayout:_flowLayout animated:false];
//    }
    [self reloadData];
}

- (void)setMinimumLineSpacing:(CGFloat)minimumLineSpacing
{
    _minimumLineSpacing = minimumLineSpacing;
    [self reloadData];
//    _flowLayout.minimumLineSpacing = minimumLineSpacing;
//    [_collectionView setCollectionViewLayout:_flowLayout animated:false];
}

- (void)setMinimumInteritemSpacing:(CGFloat)minimumInteritemSpacing
{
    _minimumInteritemSpacing = minimumInteritemSpacing;
    [self reloadData];
//    _flowLayout.minimumInteritemSpacing = minimumInteritemSpacing;
//    [_collectionView setCollectionViewLayout:_flowLayout animated:false];
}

- (void)setContentInset:(UIEdgeInsets)contentInset
{
    _contentInset = contentInset;
    [self reloadData];
}

- (void)setCellHeight:(CGFloat)cellHeight
{
    _cellHeight = cellHeight;
    [self reloadData];
}

- (void)setCellCornerRadius:(CGFloat)cellCornerRadius
{
    _cellCornerRadius = cellCornerRadius;
    [self reloadData];
}

- (void)setTitleLabelFontsize:(CGFloat)titleLabelFontsize
{
    _titleLabelFontsize = titleLabelFontsize;
    [self reloadData];
}

- (void)setSelectedItems:(NSArray<WSQSelectionItem *> *)selectedItems
{
    _selectedItems = selectedItems;
    for (WSQSelectionItem *item in selectedItems) {
        NSInteger idx = [self.items indexOfObject:item];
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]]];
        [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0] animated:false scrollPosition:UICollectionViewScrollPositionNone];
    }
}

@end
